<template>
  <div>
    <Card class="card clear-float">
      <p class="card-title" slot="title">{{$t('iaJmHNBt8LxtQZIrhE0gP')}}</p>
      <div class="menu-container">
        <div class="menu-operate">
          <span>{{$t('Kgu1atWrsDc8c7GDG0N0K')}}：</span>
          <div class="select-area">
            <Select v-model="adminType" style="width:200px" @on-change="changeAdminType">
              <!-- <Option value="0">超级管理员</Option> -->
              <Option value="1">{{$t('agt')}}</Option>
              <Option value="2">{{$t('SWJNpRnfSDK7MAg0omTmr')}}</Option>
            </Select>
          </div>
          <Button type="primary" icon="ios-checkmark" @click="update">{{$t('gtf406pXjMaOfSNPVSZdb')}}</Button>
        </div>
        <div class="menu-operate">
          <span>{{$t('bdxeIdyunJkGFMvT61U0P')}}</span>
          <span style="margin-left: 20px">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              circle
              @click="append()"
            ></el-button>
          </span>
        </div>
        <div class="menu-content">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  circle
                  type="primary"
                  size="mini"
                  @click="append(node, data)"
                >
                  <i class="el-icon-plus"></i>
                </el-button>
                <el-button
                  circle
                  type="warning"
                  size="mini"
                  @click="edit(node, data)"
                >
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button
                  circle
                  type="danger"
                  size="mini"
                  @click="remove(node, data)"
                >
                  <i class="el-icon-minus"></i>
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
        <div class="null-content" v-if="treeData.length === 0">
          <Button type="success" icon="ios-add" @click="append()">{{$t('hGl4pWOlLSDpL-TTXnLPL')}}</Button>
        </div>
      </div>
    </Card>
    <Modal
      v-model="modal"
      :title="(status === 'new' ? $t('N8xdbBoV-d6Vc33tKrGGm') : $t('3cH_U2GeBUW1V74W8oDNv')) + $t('y1ft11WrPU-guAaZvsmye')"
      footer-hide
      :mask-closable="false"
    >
      <menu-form
        :show="modal"
        :data="menu"
        :menulist="menulist"
        :rules="rules"
        :status="status"
        :parent="parent"
        @save="save"
        @close="close"
      />
    </Modal>
  </div>
</template>

<script>
import MenuForm from './components/rolemenu'
import {
  getMenuManageListInfo,
  getDefaultRoleMenuList,
  updateAdminRoleList,
  getMenuInfo
} from '@/api/data2'

const isFalse = p => {
  return _.isNil(p) || p === '' || p == 0
}

const defaults = () => {
  return {
    name: '',
    urlname: '',
    titlename: '',
    id: '',
    pid: '',
    sort: 0
  }
}

export default {
  components: {
    MenuForm
  },
  name: 'default_role_manage',
  data () {
    return {
      adminType: '1',
      menulist: [],
      data: [],
      // treeData: [],
      status: 'new',
      modal: false,
      menu: defaults(),
      rules: {
        titlename: [
          { required: true, message: this.$t('QJtx6Ibn9Qk_zM7rfQOIt'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$t('iplgI_fBBy8y30gdiCoSI'), trigger: 'blur' }
        ]
      },
      parent: null,
      defaultProps: {
        children: 'children',
        label: 'titlename'
      },
      roleData: {}
    }
  },
  computed: {
    treeData () {
      const data = this.data.map(d => {
        return _.assign({}, d, { children: [] })
      })
      _.forEach(data, d => {
        if (!isFalse(d.pid)) {
          const target = data.find(l => l.id === d.pid)
          target && target.children.push(d)
        }
      })
      const root = data.filter(d => isFalse(d.pid))
      return root
    }
  },
  async created () {
    await this.getMenuManageList()
    await this.queryData()
  },
  methods: {
    async getMenuManageList () {
      const { code, data, desc } = await getMenuManageListInfo()
      if (code == 200) {
        this.menulist = data.datalist || []
      } else {
        this.$Message.error(desc)
        this.menulist = []
      }
    },
    async queryData () {
      const { code, data, desc } = await getDefaultRoleMenuList({
        isoperatormanager: this.adminType == 1 ? 1 : 0,
        isstationmanager: this.adminType == 1 ? 0 : 1
      })
      if (code == 200) {
        this.roleData = data
        const res = []
        const menus = data.menuidlist || []
        // 测试代码，等后台调通后，使用时注释掉
        // menus = this.adminType == 1
        //     ? agentMenu
        //     : stationMenu
        menus.forEach(m => {
          const item = this.menulist.find(l => l.id == m)
          if (item) {
            res.push(
              _.assign({}, item, {
                id: item.id,
                titlename: item.titlename,
                pid: item.pid
              })
            )
          }
        })
        _.remove(res, r => {
          return !isFalse(r.pid) && !res.find(s => s.id == r.pid)
        })
        this.data = res
      } else {
        this.$Message.error(desc)
        this.data = []
      }
      // this.getTreeData()
    },
    // getTreeData () {
    //   const data = this.data.map(d => {
    //     return _.assign({}, d, { children: [] })
    //   })
    //   _.forEach(data, d => {
    //     if (!isFalse(d.pid)) {
    //       const target = data.find(l => l.id === d.pid)
    //       target && target.children.push(d)
    //     }
    //   })
    //   const root = data.filter(d => isFalse(d.pid))
    //   this.treeData = root
    // },

    append (node) {
      this.status = 'new'
      this.menu = _.assign(
        defaults(),
        node
          ? {
            pid: node.data.id
          }
          : {}
      )
      this.modal = true
      this.parent = node ? node.data : null
    },

    async edit (node, data) {
      if (!_.isNil(data.id)) {
        const { code, data: res, desc } = await getMenuInfo({
          id: data.id
        })
        if (code == 200) {
          this.status = 'edit'
          this.menu = _.assign({}, _.cloneDeep(data), { sort: res.sort })
          this.modal = true
          this.parent = node.parent
        } else {
          this.$Message.error(desc)
        }
      }
    },

    async remove (node, data) {
      // const { code, desc } = await deleteMenu({ id: data.id })
      // if (code == 200) {
      // const parent = node.parent
      // const children = parent.data.children || parent.data
      // const index = children.findIndex(d => d.id === data.id)
      // children.splice(index, 1)
      let res = [data.id]
      res = res.concat(this.data.filter(d => d.pid == data.id).map(d => d.id))
      this.data = this.data.filter(d => res.indexOf(d.id) === -1)

      // this.$Message.success('删除成功！')
      // this.queryData()
      // } else {
      //   this.$Message.error(desc)
      // }
    },

    save (data, status) {
      this.modal = false
      console.log(data)
      if (status === 'new') {
        this.data.push(data)
      } else {
        const index = this.data.findIndex(d => d.id == data.id)
        this.data.splice(index, 1, data)
      }
    },

    close () {
      this.modal = false
    },

    changeAdminType () {
      this.queryData()
    },

    async update () {
      const { code, desc } = await updateAdminRoleList({
        ...this.roleData,
        menuidlist: _.uniq(this.data.map(d => d.id))
      })
      if (code == 200) {
        this.$Message.success(desc || this.$t('zs9Qb3hoAGt6cd4DjeGow'))
      } else {
        this.$Message.error(desc || this.$t('OwnIY9rfEzi1ONovHZ6wW'))
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.custom-tree-node,
.menu-operate {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.menu-operate {
  padding-bottom: 10px;
}
.el-tree >>> .el-tree-node
  padding 8px 0
.el-tree >>> .el-tree-node .el-tree-node__content
  padding-bottom 8px
.el-tree >>> .el-tree-node__children .el-tree-node__content
  padding-bottom 0px
.select-area
  display inline-block
.null-content
  text-align center
</style>
